﻿using System.Security.Claims;
using ApiLib.AppStart;
using ApiLib.Utils;
using Furion;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ApiLib.Common;

/// <summary>
/// 全局异常处理 FriendlyExceptionFilter约定：AppFriendlyException is {ValidationException:true}不进入
/// </summary>
public class GlobalExceptionHandler : IGlobalExceptionHandler, ISingleton
{
    /// <summary>
    /// 异常处理
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public Task OnExceptionAsync(ExceptionContext context)
    {
        // 写日志
        var typeId = App.User.FindFirstValue(ClaimTypes.Sid);
        if (!string.IsNullOrEmpty(typeId))
        {
            typeId = $"用户{typeId}";
        }

        var log = $"{typeId}出现异常：{context.Exception.Message}";
        WebUtil.LogExp(log, context.Exception);
        return Task.CompletedTask;
    }
}

/// <summary>
/// 服务异常异常，会记录日志！！！
/// </summary>
public class MyServiceException : AppFriendlyException
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="message"></param>
    public MyServiceException(string message) : base(message, GlobalConfig.BaseResponseCode.Failed)
    {
    }
}

/// <summary>
/// 接口异常，用于返回异常信息。
/// </summary>
public class MyActionException : AppFriendlyException
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="message"></param>
    public MyActionException(string message) : base(message, GlobalConfig.BaseResponseCode.Failed)
    {
    }
}

/// <summary>
/// 数据验证异常，不记录日志！！！
/// </summary>
public class MyValidationException : AppFriendlyException
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="message"></param>
    public MyValidationException(string message) : base(message, GlobalConfig.BaseResponseCode.Failed)
    {
        ValidationException = true;
    }
}

/// <summary>
/// 认证失败异常
/// </summary>
public class MyAuthenticationFailureException : AppFriendlyException
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="message"></param>
    public MyAuthenticationFailureException(string message) : base(message, GlobalConfig.BaseResponseCode.AuthenticationFailure)
    {
    }
}

/// <summary>
/// 未授权访问
/// </summary>
public class MyUnauthorizedAccessException : AppFriendlyException
{
    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="message"></param>
    public MyUnauthorizedAccessException(string message) : base(message, GlobalConfig.BaseResponseCode.UnauthorizedAccess)
    {
    }
}